package com.zzg.springboot.validate;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

import com.zzg.springboot.entity.SecurityUserEntity;
import com.zzg.springboot.entity.UserEntity;
import com.zzg.springboot.service.UserEntityService;

public class SmsAuthenticationProvider implements AuthenticationProvider {

    private UserEntityService userDetailService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        SmsAuthenticationToken authenticationToken = (SmsAuthenticationToken) authentication;
        //UserDetails userDetails = userDetailService.findByName((String) authenticationToken.getPrincipal());
        UserEntity userEntity = userDetailService.findByName((String) authenticationToken.getPrincipal());
        UserDetails userDetails = new SecurityUserEntity(userEntity);
        if (userDetails == null){
        	throw new InternalAuthenticationServiceException("未找到与该手机号对应的用户");        	
        }

        SmsAuthenticationToken authenticationResult = new SmsAuthenticationToken(userDetails, userDetails.getAuthorities());
        authenticationResult.setDetails(authenticationToken.getDetails());
        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return SmsAuthenticationToken.class.isAssignableFrom(aClass);
    }

	public UserEntityService getUserDetailService() {
		return userDetailService;
	}

	public void setUserDetailService(UserEntityService userDetailService) {
		this.userDetailService = userDetailService;
	}
    
    

  
}
